package com.xiemulei.gulimall.member.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiemulei.common.utils.HttpUtils;
import com.xiemulei.common.utils.PageUtils;
import com.xiemulei.common.utils.Query;
import com.xiemulei.common.vo.SocialUserVo;
import com.xiemulei.common.vo.UserLoginVo;
import com.xiemulei.gulimall.member.dao.MemberDao;
import com.xiemulei.gulimall.member.dao.MemberLevelDao;
import com.xiemulei.gulimall.member.entity.MemberEntity;
import com.xiemulei.gulimall.member.entity.MemberLevelEntity;
import com.xiemulei.gulimall.member.exception.PhoneExistsException;
import com.xiemulei.gulimall.member.exception.UsernameExistsException;
import com.xiemulei.gulimall.member.service.MemberService;
import com.xiemulei.gulimall.member.vo.MemberRegisterVo;
import jakarta.annotation.Resource;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Resource
    MemberLevelDao memberLevelDao;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(MemberRegisterVo vo) {
        MemberEntity memberEntity = new MemberEntity();
        // 设置默认会员等级
        MemberLevelEntity memberLevelEntity = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(memberLevelEntity.getId());

        // 唯一性验证，使用异常机制
        checkPhoneUnique(vo.getPhone());
        checkUsernameUnique(vo.getUsername());

        memberEntity.setMobile(vo.getPhone());
        memberEntity.setUsername(vo.getUsername());

        // 密码加密存储
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode(vo.getPassword());
        memberEntity.setPassword(encode);


        baseMapper.insert(memberEntity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistsException {
        Long count = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (count > 0) {
            throw new PhoneExistsException();
        }
    }

    @Override
    public void checkUsernameUnique(String username) throws UsernameExistsException {
        Long count = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (count > 0) {
            throw new UsernameExistsException();
        }
    }

    @Override
    public MemberEntity login(UserLoginVo vo) {
        String username = vo.getUsername();
        String password = vo.getPassword();
        MemberDao memberDao = this.baseMapper;
        MemberEntity entity = memberDao.selectOne(
                new QueryWrapper<MemberEntity>()
                        .eq("username", username)
                        .or()
                        .eq("mobile", username));
        if (entity == null) {
            return null;
        } else {
            String encoded = entity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            boolean matches = passwordEncoder.matches(password, encoded);
            if (matches) {
                return entity;
            } else {
                return null;
            }
        }
    }

    @Override
    public MemberEntity login(SocialUserVo socialUserVo) {
        String uid = socialUserVo.getUid();
        MemberDao memberDao = this.baseMapper;
        // 根据社交账号 uid 查询是否登陆过
        MemberEntity member = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (member != null) {
            // 登陆过，更新账号信息
            MemberEntity update = new MemberEntity();
            update.setId(member.getId());
            update.setAccessToken(socialUserVo.getAccess_token());
            update.setExpiresIn(socialUserVo.getExpires_in());

            memberDao.updateById(update);

            member.setAccessToken(socialUserVo.getAccess_token());
            member.setExpiresIn(socialUserVo.getExpires_in());
            return member;
        } else {
            MemberEntity register = new MemberEntity();
            // 设置默认会员等级
            MemberLevelEntity memberLevelEntity = memberLevelDao.getDefaultLevel();
            register.setLevelId(memberLevelEntity.getId());
            try {
                // 查询社交账号的个人信息
                Map<String, String> query = new HashMap<>();
                query.put("access_token", socialUserVo.getAccess_token());
                query.put("uid", socialUserVo.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "GET", new HashMap<>(), query);
                if (response.getStatusLine().getStatusCode() == 200) {
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(json);
                    String name = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");

                    register.setNickname(name);
                    register.setGender("m".equals(gender) ? 1 : 0);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            register.setSocialUid(socialUserVo.getUid());
            register.setAccessToken(socialUserVo.getAccess_token());
            register.setExpiresIn(socialUserVo.getExpires_in());

            memberDao.insert(register);

            return register;
        }
    }
}